import inquirer from 'inquirer'
import request from 'request'
import { managePm2 } from '../pm2.js'

const PROCESS_ID = 0; // 要管理的进程ID  
const APP_PATH = './src/signIn/http.js'; // 要启动的应用路径  
import { manualCheckIn } from './manualCheckIn.js'
import spawn from 'cross-spawn'
import fs from 'node:fs'
import path from 'node:path'
const fileName = '.config.json';
const userDir = process.env.USERPROFILE || process.env.HOME;
const filePath = path.join(userDir, fileName);

import { fileURLToPath } from 'url';
import { dirname } from 'path';

export const automaticCheckIn = async () => {
  if (fs.existsSync(filePath)) {
    const optionsConfig = [
      {
        type: "confirm",
        message: "是否重新配置文件",
        name: "genderConfirm",
        suffix: "必答题",
      }
    ];
    inquirer.prompt(optionsConfig).then(async (res) => {
      if (res.genderConfirm) {
        const options = [
          {
            type: 'input',
            name: 'getCookie',
            message: '请输入你的cookie',
          },
          {
            type: 'input',
            name: 'getAid',
            message: '请输入你的aid',
          },
          {
            type: 'input',
            name: 'getUid',
            message: '请输入你的uid',
          },
          {
            type: 'input',
            name: 'gethHour',
            message: '请输入你的定时的小时',
            validate: function (value) {
              if (value.length) {
                return true;
              } else {
                return '小时不能为空';
              }
            }
          },
          {
            type: 'input',
            name: 'getMinute',
            message: '请输入你的定时分钟',
            validate: function (value) {
              if (value.length) {
                return true;
              } else {
                return '分钟不能为空';
              }
            }
          },
        ];
        const answers = await inquirer.prompt(options)
        const cookie = `sessionid=${answers.getCookie}`
        const url = 'https://juejin.cn/'
        const check_url = `https://api.juejin.cn/growth_api/v1/check_in?aid=${answers.getAid}&uid=${answers.getUid}`
        const configData = {
          cookie,
          url,
          check_url,
          hour: answers.gethHour, minute: answers.getMinute,
        };
        const configString = `${JSON.stringify(configData, null, 2)}`;
        fs.writeFile(filePath, configString, 'utf8', (err) => {
          if (err) {
            console.error('写入文件时发生错误:', err);
            return;
          }
        });
        regularTime()
      } else {
        let jsonData = await readFile(filePath)
        if (!jsonData.hour) {
          const options = [
            {
              type: 'input',
              name: 'gethHour',
              message: '请输入你的定时的小时',
              validate: function (value) {
                if (value.length) {
                  return true;
                } else {
                  return '小时不能为空';
                }
              }
            },
            {
              type: 'input',
              name: 'getMinute',
              message: '请输入你的定时分钟',
              validate: function (value) {
                if (value.length) {
                  return true;
                } else {
                  return '分钟不能为空';
                }
              }
            },
          ];
          const answers = await inquirer.prompt(options)
          jsonData = { ...jsonData, hour: answers.gethHour, minute: answers.getMinute, }
          console.log(answers, 'answers', jsonData)
          const configString = `${JSON.stringify(jsonData, null, 2)}`;
          fs.writeFile(filePath, configString, 'utf8', (err) => {
            if (err) {
              console.error('写入文件时发生错误:', err);
              return;
            }
          });
        }
        regularTime()
      }
    })
  }
}
const regularTime = () => {
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = dirname(__filename);

  console.log(__dirname); // 输出当前文件的所在目录
  console.log(path.join(__dirname, 'http.js'))
  // 执行主逻辑  
  managePm2(PROCESS_ID,APP_PATH);
}
const readFile = async (filePath) => {
  return new Promise((resolve, reject) => {
    try {
      fs.readFile(filePath, 'utf8', async (err, data) => {
        if (err) {
          console.error(`读取文件时出错: ${err}`);
          reject(err)
        } else {
          const jsonData = JSON.parse(data);
          console.log('读取到本地配置，开始签到')
          resolve(jsonData)
        }
      })
    } catch (err) {
      console.error(err);
      reject(err)
    }
  })
}
